import request from '@/util/request'

async function login(username, password) {
	return (
		await request.post('/login', {username, password})
	).data
}

async function register(username, password) {
	return (
		await request.post('/user/register', {username, password, confirmPassword: password})
	).data
}

/**
 * 生成10以下两数的算术运算
 * @returns {Object} 包含两个随机数和运算结果的对象
 */
function generateRandomArithmetic() {
	let result = '-1';

	while (eval(result) < 0) {
		// 生成两个1-9的随机整数（10以下）
		const num1 = Math.floor(Math.random() * 9) + 1;
		const num2 = Math.floor(Math.random() * 9) + 1;
		// 随机选择一种运算符（+、-、*、/）
		const operators = ['+', '-'];
		const operator = operators[Math.floor(Math.random() * operators.length)];
		result = `${num1} ${operator} ${num2}`
	}
    return result
}

var status = {
	currentUserId: null,
}

function updateLoginStatus(userId, token) {
	status.currentUserId = userId
	request.defaults.headers.common['Authorization'] = 'Bearer ' + token
	sessionStorage.setItem('userId', userId)
	sessionStorage.setItem('token', token)
}

function getCurrentUserId() {
	return sessionStorage.getItem('userId')
}

async function isAdmin() {
	const id = getCurrentUserId()
	if (!Number.isInteger(parseInt(id))) {
		console.log("用户ID获取失败")
		return
	}
	const user = (await request.get(`/user/${id}`)).data.data
	return user.isAdmin
}

const loginUtil = {
	login,
	register,
	generateRandomArithmetic,
	status,
	updateLoginStatus,
	getCurrentUserId,
	isAdmin
}

export {loginUtil}